<template>
    <el-form ref="navForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item label="描述" prop="nav_text">
            <el-input v-model="ruleForm.nav_text" />
        </el-form-item>

        <el-form-item label="时间" required>
            <el-col :span="11">
                <el-form-item prop="nav_create_time">
                    <el-date-picker v-model="ruleForm.nav_create_time" type="date" label="" placeholder="开始"
                        style="width: 100%" disabled />
                </el-form-item>
            </el-col>
            <el-col class="text-center" :span="2">
                <span class="text-gray-500"></span>
            </el-col>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="addNavigate(navForm)">发布</el-button>
            <el-button @click="resetForm(navForm)">重置</el-button>
        </el-form-item>
    </el-form>
</template>
<script lang="ts" setup>
// 导入格式化时间插件
import moment from "moment";
// 导入消息提示框
import { ElMessage } from 'element-plus';
// 导入定义数据的方法
import { ref, reactive, onMounted } from 'vue';
// 导入表单组件对象
import type { FormInstance, FormRules } from 'element-plus';
// 导入相关接口
import { navAddApi, navModifyApi, navDetailApi } from '../../http/request';
// 导入创建路由方法
import { useRouter } from 'vue-router';
// 定义路由
const $router = useRouter();
// 定义变量
let nav_id: any = ref("");
// 获取token
let token: any = localStorage.getItem('token');
// 定义导航表单实例
const navForm = ref<FormInstance>();
// 定义对象记录表单提交的数据
const ruleForm = reactive({
    nav_create_time: '',
    nav_text: ''
})
// 设置表单约束
const rules = reactive<FormRules>({
    // 创建时间
    nav_create_time: [
        {
            type: 'date',
            required: true,
            message: '请选择一个时间',
            trigger: 'change',
        },
    ],
    // 描述文字
    nav_text: [
        { required: true, message: '请输入导航描述', trigger: 'blur' },
    ],
})
// 设置时间（默认）
ruleForm.nav_create_time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
// 编写添加导航方法
const addNavigate = async (formObj: FormInstance | undefined) => {
    if (!formObj) return
    await formObj.validate(async (valid, fields) => {
        if (valid) {
            let { nav_text } = ruleForm;
            let formData = new FormData();
            formData.append("token", token);
            formData.append('nav_text', nav_text);
            if (nav_id.value) {
                // 修改导航
                formData.append("nav_id", nav_id.value)
                navModifyApi({ token, nav_id: nav_id.value, nav_text })
                    .then(
                        (data: any) => {
                            if (data.code == 200) {
                                // 延迟300ms跳转页面
                                let timeout = setTimeout(() => {
                                    // 重置表单
                                    formObj.resetFields();
                                    $router.push({ path: '/navigate/list' });
                                    clearTimeout(timeout);
                                }, 300)
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'success',
                                });
                            } else {
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'warning',
                                });
                            }
                        }
                    ).catch(
                        err => {
                            console.log(err)
                        }
                    )
            } else {
                // 添加导航
                navAddApi({ token, nav_text })
                    .then(
                        (data: any) => {
                            // console.log(data)
                            if (data.code == 200) {
                                // 延迟300ms跳转页面
                                let timeout = setTimeout(() => {
                                    // 重置表单
                                    formObj.resetFields();
                                    $router.push({ path: '/navigate/list' });
                                    clearTimeout(timeout);
                                }, 300)
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'success',
                                });
                            } else {
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'warning',
                                });
                            }
                        }
                    )
                    .catch(
                        err => {
                            console.log(err)
                        }
                    )
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 编写重置导航方法（轮播图）
const resetForm = (formObj: FormInstance | undefined) => {
    if (!formObj) return
    formObj.resetFields()
}
// // 获取上传文件行为
// const handleImgChange = (event: any) => {
//     let file = event['raw'];
//     // console.log("file:", file)
// }
// 获取导航详情
const detailNav = (nav_id: any) => {
    // 获取导航详情
    navDetailApi({ token, nav_id: nav_id.value })
        .then(
            (data: any) => {
                // console.log('3.0', data)
                if (data.code == 200) {
                    let { nav_create_time, nav_text } = data.result[0];
                    ruleForm.nav_create_time = nav_create_time;
                    ruleForm.nav_text = nav_text;
                }
            }
        )
        .catch(
            error => {
                console.log(error);
            }
        )
}
// 调用挂载钩子函数
onMounted(() => {
    // 初始化导航
    // console.log(nav_id)
    if ($router && $router.currentRoute.value.query) {
        nav_id.value = $router.currentRoute.value.query.nav_id
        // console.log(nav_id.value)
        if (nav_id.value) {
            detailNav(nav_id)
        }
    }
})
</script>
<style lang="scss">
.el-upload-dragger {
    margin-bottom: 20px;
    padding-top: 0px;
    padding-bottom: 0px;

    div {
        padding: 0 !important;
        margin: 0 !important;
    }
}

.demo-ruleForm {
    ::v-deep .el-picker-panel__body {
        z-index: 100000000000;
        background-color: #ccc;
    }
}
</style>